﻿using CefSharp;
using CefSharp.Wpf;
using PidKeyReptile.Desktop.Helper;
using PidKeyReptile.Desktop.ViewModel;
using Stylet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace PidKeyReptile.Desktop.Pages.Checker
{
    public class CheckerManagerViewModel : Screen
    {
        public readonly IWindowManager windowManager;

        private TaskWindowModel _selectTaskTabs;
        public TaskWindowModel SelectTaskTabs
        {
            get { return _selectTaskTabs; }
            set { SetAndNotify(ref _selectTaskTabs, value); }
        }


        private ObservableCollection<TaskWindowModel> _taskWindowList;
        public ObservableCollection<TaskWindowModel> TaskWindowList
        {
            get { return _taskWindowList; }
            set { SetAndNotify(ref _taskWindowList, value); }
        }

        private int _sliderSpeed = 6;
        public int SliderSpeed
        {
            get { return _sliderSpeed; }
            set { SetAndNotify(ref _sliderSpeed, value); }
        }


        //执行方案
        private BoundObject _boundObject;

        public CheckerManagerViewModel(IWindowManager windowManager)
        {
            this.windowManager = windowManager;

            TaskWindowList = new ObservableCollection<TaskWindowModel>();
            _taskWindowList.Add(BuildTaskModel());
            _selectTaskTabs = _taskWindowList[0];

            _boundObject = new BoundObject(this);
        }
        /// <summary>
        /// 增加任务
        /// </summary>
        public void AddTask()
        {
            TaskWindowList.Add(BuildTaskModel());
        }

        /// <summary>
        /// 减少任务
        /// </summary>
        public void ReduceTask()
        {
            if (TaskWindowList.Count == 1) return;
            var remove = TaskWindowList.LastOrDefault();
            remove.WebBrowser.Dispose();
            TaskWindowList.Remove(remove);
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        public void PauseTask()
        {
            foreach (var item in _taskWindowList)
            {
                item.WebBrowser.GetMainFrame().EvaluateScriptAsync("isrun=false");
            }
        }

        /// <summary>
        /// 开始任务
        /// </summary>
        public void StartTask()
        {
            foreach (var item in _taskWindowList)
            {
                item.WebBrowser.GetMainFrame().EvaluateScriptAsync("isrun=true");
                item.WebBrowser.GetMainFrame().EvaluateScriptAsync("BeginChecker()");
            }
        }

        public void ToolCmd()
        {
            SelectTaskTabs.WebBrowser.ShowDevTools();
        }
        protected override void OnPropertyChanged(string propertyName)
        {
            if (propertyName == nameof(SliderSpeed))
            {
                _selectTaskTabs.WebBrowser.GetMainFrame().EvaluateScriptAsync($"speed={_sliderSpeed * 1000}");
            }
            base.OnPropertyChanged(propertyName);
        }

        private TaskWindowModel BuildTaskModel()
        {
            var browser = new ChromiumWebBrowser();
            var mode = new TaskWindowModel()
            {
                IsRun = true,
                Name = $"任务{_taskWindowList.Count + 1}",
                WebBrowser = browser,
            };
            CefSharpSettings.WcfEnabled = true;
            browser.RequestHandler = new CheckerRequestHandler();
            browser.Address = "https://khoatoantin.com/pidms";
            browser.BrowserSettings.ImageLoading = CefState.Disabled;
            browser.IsBrowserInitializedChanged += (t, s) =>
            {
                if (browser.IsDisposed) return;
                browser.GetCookieManager().SetCookieAsync("https://khoatoantin.com/pidms", new Cookie()
                {
                    Name = "userlogin",
                    Path = "/",
                    Value = "usersettings=6Y6J10PXuqzKxk6kYtsmQNb8QZLN41TB3BfFXKBOhw/nWUqqE5UVkpzMe8jRCDP92w7zAl/PnPTRHax/O50kDdZNzG1OoCSDmKDYc1YQFquyiFly3LLp/9lg+thKbYeiBpNrHGKyOkBsicVNQUSKtEBOjqW9eAIkVyuWUrqLIGeCOAPW4EreXXA/FJeexYStMbWlmM3dzfVkpsHGxuJ9tMRQSFdYLvNCrBzqnCmNQJD4AvHtBuikqyxYgEwRoiHR+rO5YgsBh0OLPz2ojD6/cDEZ/CvhXKF3VM3VoUKo24k8X8GoHpqpCAVWZV4fBkwRcfYOGVVWp50BpLfdg+lH4g==",
                });

                browser.JavascriptObjectRepository.Register("boundAsync", _boundObject, true, BindingOptions.DefaultBinder);
            };

            return mode;
        }

    }
}
